package com.igeek.mygh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.igeek.mygh.Sample;
import com.igeek.mygh.TTLQueue.SendMsgUtil;
import com.igeek.mygh.VerificationCode;
import com.igeek.mygh.model.TTLMsg;
import com.igeek.mygh.model.user.User;
import com.igeek.mygh.result.Result;
import com.igeek.mygh.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javafx.scene.input.DataFormat;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author xlz;
 * @data 2022-08-01 20:24
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户管理接口")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SendMsgUtil sendMsgUtil;



    @ApiOperation(value = "发送验证码至Redis")
    @PostMapping("/login/sendCode/{phone}")
    public Result sendCode(
            @ApiParam(name="phone",value = "手机号",required = true)@PathVariable("phone")String phone
    ) throws Exception {
        if (phone!=null && !phone.equals("")){
            Boolean flag = redisTemplate.hasKey(phone);
            if (!flag){
                //向Redis中存入key(phone) -value(随机6位数)   及过期时间
                int code =VerificationCode.getVFCode();
                redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
                Sample sample = new Sample();
                sample.sendSMS(phone,String.valueOf(code));
                log.info("send over");
                return Result.ok();
            }else return Result.fail().message("请勿重复请求验证码!!!");

        }else return Result.fail().message("您输入的手机号格式错误!!!");
    }

    @ApiOperation(value = "手机号密码登录")
    @PostMapping("/login/{phone}/{password}/{code}")
    public Result userLogin(
//            @ApiParam(name="phone",value = "手机号",required = true)@PathVariable("phone")String phone,
//            @ApiParam(name="password",value = "密码",required = false)@PathVariable("password")String password,
            @ApiParam(name="code",value = "验证码",required = false)@PathVariable(value = "code",required = false)String code,
            @RequestBody User user
            ){

        User one =null;
        //获取手机号
        String phone = user.getPhone();
        //处理验证码
        Boolean flag = redisTemplate.hasKey(phone);
        if (flag){
            //处理验证码,进行验证
            if (code==null&&!code.equals("")){
                return Result.fail().message("请输入验证码!!!");
            }else {
                //获取验证码进行对比
                Object o = redisTemplate.opsForValue().get(phone);
                log.info("code = {}",code);
                if (o.toString().equals(code)){
                    QueryWrapper query = new QueryWrapper();
                    if(StringUtils.hasLength(phone)){
                        query.eq("phone",phone);
                    }
                    one = userService.getOne(query);
                    return Result.ok(one);
                }else return Result.fail().message("验证码错误!!!");
            }
        }else {
            //redis中没有验证码，则通过手机号密码查询
            QueryWrapper queryWrapper = new QueryWrapper();
            if(StringUtils.hasLength(phone)){
                queryWrapper.eq("phone",phone);
            }
            //获取密码
            String password = user.getPassword();
            if (StringUtils.hasLength(password)){
                queryWrapper.eq("password",password);
            }
            queryWrapper.eq("is_deleted",0);
            one = userService.getOne(queryWrapper);
            if (one!=null && !one.equals("")){
                return Result.ok(one);
            }
            else return Result.fail().message("账号密码错误！！！");
        }
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register/{user}")
    public Result userRegister(
            @RequestBody User user
    ){
        boolean flag = userService.save(user);
        if (flag){
            return Result.ok();
        }
        return Result.fail();
    }

    @ApiOperation(value = "定时短信")
    @PostMapping("/sendMsg/{phone}/{msg}/{ttl}")
    public Result sendTTLMsg(
            @ApiParam(name="phone",value = "手机号",required = true)@PathVariable("phone")String phone,
            @ApiParam(name="msg",value = "短信内容",required = true)@PathVariable("msg")String msg,
            @ApiParam(name="ttl",value = "定时时长/分钟",required = true)@PathVariable("ttl")Integer ttl
//            @RequestBody TTLMsg ttlMsg
    ){
//        String phone = ttlMsg.getPhone();
//        String msg = ttlMsg.getMsg();
//        Integer ttl = ttlMsg.getTtl();
        sendMsgUtil.sendDelayedMsg(phone,msg,ttl);
        return Result.ok().message("发送成功！！！");
    }

}
